<template>

  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭" okText="发送"> 
    <div class="table-operator" style="margin-bottom:24px">
      <a-button @click="handleList" type="primary" icon="plus">新增</a-button>
      <a-button icon="delete" @click="handleDelete">删除</a-button>
    </div>
    <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="rowKey"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <span slot="receiveUser" slot-scope="text, record">
           <a-input placeholder="点击选择" v-model="record.receiveRealname" readOnly   >
           
           <a-tooltip slot="suffix" title="添加人员">
            <a-icon type="plus"   @click="selectUser(record)"/>
          </a-tooltip>
          </a-input>
        </span>
      
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
        </span>

      </a-table>
     
       <user-select ref="userSelect" @setResult="setResult" :origin-target-keys="originTargetKeys"/>
     
       <table-select-modal :listUrl="'libraryCompany/hteLibCompany/pageList'" :params="{companyStatus:3}" :importColumns="companyColumns" ref="company" @ok="companyOk"></table-select-modal>
  </j-modal>
</template>

<script>
import { strNotNull } from '@/utils/common.js'

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { mixinDevice } from '@/utils/mixin'
  import { httpAction, getAction,postAction } from '@/api/manage'
import {randomUUID} from '@/utils/util'
import cloneDeep from 'lodash/cloneDeep'
const baseColumns ={
    fileId:null,
    companyName:null,
    companyId:null,
    receiveUser:null,
    receiveRealname:null,
    id:null
  }
  export default {
    name: 'HteLibCompanyPushTableModal',
     mixins:[JeecgListMixin,mixinDevice],
    components: {
        UserSelect: () => import('@/components/tools/UserSelect'),
        TableSelectModal:()=> import('@/components/tools/TableSelectModal'),
       

    },
    props: {
     
    },
    data () {
      return {
        fileId:0,
      disableMixinCreated:true,
     currSel: {},
      originTargetKeys: [],
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource:[],
    
      /* table加载状态 */
      loading:false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],

        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          
          {
            title:'公司名称',
            align:"center",
            dataIndex: 'companyName'
          },
          {
            title:'接收人',
            align:"center",
            dataIndex: 'receiveUser',
            scopedSlots: { customRender: 'receiveUser' }
          },
          
        ],  
        url: {
          list: "/libraryCompany/hteLibCompanyPush/list",
          delete: "/libraryCompany/hteLibCompanyPush/delete",
          deleteBatch: "/libraryCompany/hteLibCompanyPush/deleteBatch",
          exportXlsUrl: "/libraryCompany/hteLibCompanyPush/exportXls",
          importExcelUrl: "libraryCompany/hteLibCompanyPush/importExcel",
          getCompany: '/libraryCompany/hteLibCompanyPush/',
          queryCompanyByPolicy:'/libraryCompany/hteLibCompany/queryCompanyByPolicy',
          send:'/libraryCompany/hteLibCompanyPush/send'
        },
        dictOptions:{},
        superFieldList:[],
        title:'政策推送',
        width:800,
        visible: false,
        disableSubmit: false,
       companyColumns:[
         
          
          {
            title:'公司名称',
            align:"center",
            dataIndex: 'name'
          }
        ]
      }
    },
    methods: {

       setResult(result) {
      var usernames = []
      var realnames = []
      if (result != null) {
        result.forEach((item) => {
          usernames.push(item.username)
          realnames.push(item.realname)
        })
      }
      this.currSel.receiveUser = usernames.join(',')
      this.currSel.receiveRealname = realnames.join(',')
    },
    selectUser(col) {
      this.currSel = col
      debugger
      this.originTargetKeys = strNotNull(col.receiveUser) ? col.receiveUser.split(',') : []
      this.$refs.userSelect.doSelect()
    },
    doSelect() {
      this.visible = true
    },
    loadData(fileId) {
      this.fileId=fileId
      //加载数据 若传入参数1则加载第一页的内容
     
      var params = {};//查询条件
      params.pageNo = 1 ;
      params.pageSize = -1;
      params.fileId = fileId;
      this.loading = true;
      
      getAction(this.url.queryCompanyByPolicy, params).then((res) => {
        if (res.success) {
        
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        
          this.dataSource = this.dataHandle(res.result.records)
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }
        if(res.code===510){
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },
    dataHandle(arr){
      let that = this
      let data = []
      arr.forEach(item=>{
        let obj = cloneDeep(baseColumns) ;
        obj.rowKey = randomUUID () 
        obj.fileId = that.fileId;
        obj.companyName = item.name;
        obj.companyId = item.id
        data.push(obj)
      })
      return data 
    },
      open (fileId) {
        
          this.visible=true
        this.$nextTick(()=>{

          this.loadData(fileId);
        })
      },
      edit (record) {
        this.visible=true
        this.$nextTick(()=>{
          this.$refs.realForm.edit(record);
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
         var that = this;
        if(!that.dataSource || that.dataSource.length<=0){
           this.$message.warning('请选择推送公司！');
           return;
        }
          postAction(that.url.send, that.dataSource).then((res) => {
              if(res.success){
                 that.$message.success(res.message)
                 that.close()
              }else{
                this.$message.warning(res.message);
              }
          })
      },
      submitCallback(){
        this.$emit('ok');
        this.visible = false;
      },
      handleCancel () {
        this.close()
      },
       handleDelete: function () {

      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
      
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
              
              for (var a = 0; a < that.selectedRowKeys.length; a++) {
               let rowIndex = that.selectedRowKeys[a] ;
               
               that.dataSource.splice(that.dataSource.findIndex(item=>item.rowKey == rowIndex),1)
              }

            that.onClearSelected();
           
          }
        });
      }
    },
    handleList(){
      this.$refs.company.open();
      this.$refs.company.title = '公司添加'
    },
    companyOk(res){
      let addData = [...res]
      for (let index = 0; index < addData.length; index++) {
          let element = addData[index]
          if(!!this.dataSource.find(item=>{return item.companyName == element.name})) {
            this.$message.warning(`${element.name}已存在`);
           return;
        }
      }
      addData = this.dataHandle(addData)
      this.$refs.company.close()

      this.dataSource.push(...addData)
    }
    }
  }
</script>